package com.moshang.blog.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moshang.blog.core.constant.CurrentUser;
import com.moshang.blog.core.enums.OnlineStatus;
import com.moshang.blog.core.utils.*;
import com.moshang.blog.entity.SysUserOnline;
import com.moshang.blog.mapper.SysUserOnlineMapper;
import com.moshang.blog.service.SysUserOnlineService;
import eu.bitwalker.useragentutils.UserAgent;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * @program: blog
 * @description: ${description}
 * @author: moshang
 * @create: 2018-12-19 14:23
 **/
@Service
public class SysUserOnlineServiceImpl extends ServiceImpl<SysUserOnlineMapper,SysUserOnline> implements SysUserOnlineService {
    @Resource
    private SysUserOnlineMapper userOnlineMapper;
    @Resource
    private SessionDAO sessionDAO;

    public void save() {
        List<SysUserOnline> list = new ArrayList<>();
        Collection<Session> sessions = sessionDAO.getActiveSessions();
        UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        // 获取客户端操作系统
        String os = userAgent.getOperatingSystem().getName();
        // 获取客户端浏览器
        String browser = userAgent.getBrowser().getName();
        for (Session session : sessions) {
            SysUserOnline userOnline = new SysUserOnline();
            if (session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY) == null) {
                continue;
            } else {
                SimplePrincipalCollection principalCollection = (SimplePrincipalCollection) session
                        .getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
                CurrentUser user = (CurrentUser) principalCollection.getPrimaryPrincipal();
                userOnline.setLoginName(user.getUserName());
            }
            userOnline.setSessionId((String) session.getId());
            userOnline.setIpAddr(IpUtils.getIpAddr());
            userOnline.setLoginLocation(AddressUtils.getRealAddressByIP(session.getHost()));
            userOnline.setStartTimestamp(session.getStartTimestamp());
            userOnline.setLastAccessTime(session.getLastAccessTime());
            userOnline.setBrowser(browser);
            userOnline.setOs(os);
            Long timeout = session.getTimeout();
            if (timeout == 0L) {
                userOnline.setStatus(OnlineStatus.off_line);
            } else {
                userOnline.setStatus(OnlineStatus.on_line);
            }
            userOnline.setExpireTime(session.getTimeout());
            userOnlineMapper.saveOnline(userOnline);
        }
    }
    /**
     * 通过会话序号查询信息
     *
     * @param sessionId 会话ID
     * @return 在线用户信息
     */
    @Override
    public SysUserOnline selectOnlineById(String sessionId)
    {
        return userOnlineMapper.selectOnlineById(sessionId);
    }

    /**
     * 通过会话序号删除信息
     *
     * @param sessionId 会话ID
     * @return 在线用户信息
     */
    @Override
    public void deleteOnlineById(String sessionId)
    {
        SysUserOnline userOnline = selectOnlineById(sessionId);
        if (StringUtils.isNotNull(userOnline))
        {
            userOnlineMapper.deleteOnlineById(sessionId);
        }
    }

    /**
     * 通过会话序号删除信息
     *
     * @param sessions 会话ID集合
     * @return 在线用户信息
     */
    @Override
    public void batchDeleteOnline(List<String> sessions)
    {
        for (String sessionId : sessions)
        {
            SysUserOnline userOnline = selectOnlineById(sessionId);
            if (StringUtils.isNotNull(userOnline))
            {
                userOnlineMapper.deleteOnlineById(sessionId);
            }
        }
    }

    /**
     * 保存会话信息
     *
     * @param online 会话信息
     */
    @Override
    public void saveOnline(SysUserOnline online)
    {
        userOnlineMapper.saveOnline(online);
    }

    /**
     * 查询会话集合
     *
     * @param userOnline 在线用户
     */
    @Override
    public List<SysUserOnline> selectUserOnlineList(SysUserOnline userOnline)
    {
        return userOnlineMapper.selectUserOnlineList(userOnline);
    }

    /**
     * 强退用户
     *
     * @param sessionId 会话ID
     */
    @Override
    public void forceLogout(String sessionId)
    {
        userOnlineMapper.deleteOnlineById(sessionId);
    }

    /**
     * 查询会话集合
     *
     * @param expiredDate 失效日期
     */
    @Override
    public List<SysUserOnline> selectOnlineByExpired(Date expiredDate)
    {
        String lastAccessTime = Lang3DateUtils.parseDateToStr(Lang3DateUtils.YYYY_MM_DD_HH_MM_SS, expiredDate);
        return userOnlineMapper.selectOnlineByExpired(lastAccessTime);
    }
}
